package storage

import (
	"EnjoyWorking/config"
	"EnjoyWorking/model"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/kataras/golog"
)

var engine *gorm.DB

func MySqlDb() *gorm.DB {
	return engine
}

/**
 * 实例化数据库引擎方法：mysql的数据引擎
 */
func NewMysqlEngine() {
	database := config.AppConfig().DataBase
	url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", database.User, database.Pwd, database.Host, database.Port, database.Database)

	var(
		db   *gorm.DB
		err  error
	)

	if db, err = gorm.Open("mysql", url); err != nil {
		goto ERR
	}
	if err = db.DB().Ping(); err != nil {
		goto ERR
	}
	//一个坑，不设置这个参数，gorm会把表名转义后加个s，导致找不到数据库的表
	db.SingularTable(true)
	db.LogMode(config.AppConfig().DataBase.ShowSql)
	db.DB().SetMaxOpenConns(config.AppConfig().DataBase.MaxOpenConns)
	db.DB().SetMaxIdleConns(config.AppConfig().DataBase.MaxIdleConns)

	db.AutoMigrate(
		&model.User{},
		&model.Department{},
		&model.Job{},
		&model.InterfaceDetail{},
		&model.Project{},
		&model.Wpr{},
		&model.WprItem{})

	engine = db
	return
ERR:
	golog.Fatalf("~~> Mysql的gorm初始化错误,原因:%s", err.Error())
	return
}

